/*
 * ClientSocket.cpp
 *
 * Author: Grupo Nro.
 */

#include "ClientSocket.h"

ClientSocket::ClientSocket(string ip_servidor, int puerto_servidor) {
	this->ip_servidor = ip_servidor;
	this->puerto_servidor = puerto_servidor;
	this->sockfd = -1;
}

ClientSocket::~ClientSocket() {
}

int ClientSocket::getSockfd(){
	return this->sockfd;
}

void ClientSocket::conectar(){
	//Socket internet, y un Stream (TCP)
	if ((this->sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
		string mensajeError = "Error al crear socket.";
		throw ComunicacionException(mensajeError);
	}

	//Infomacion de la direccion de destino
	struct sockaddr_in their_addr;

	//Estructura con la dirección y puerto destino
	their_addr.sin_family = AF_INET; //Orden de bytes de la maquina
	their_addr.sin_port = htons(this->puerto_servidor);
	their_addr.sin_addr.s_addr = inet_addr(this->ip_servidor.c_str());
	//Poner a cero el resto de la estructura
	memset(&(their_addr.sin_zero), '\0', 8);

	//Conecta
	if (connect(this->sockfd, (struct sockaddr *)&their_addr,
			sizeof(struct sockaddr)) == -1){
		string mensajeError = "Error al intentar conectarse.";
		throw ComunicacionException(mensajeError);
	}
}

void ClientSocket::shutdownConexion(){
	if (this->sockfd > 0){
		shutdown(this->sockfd, SHUT_RDWR);
	}
}

void ClientSocket::matarConexion(){
	if (this->sockfd > 0){
		close(this->sockfd);
		this->sockfd = -1;
	}
}
